package com.ssmShiro.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.ssmShiro.dao.UserRoleMapper;
import com.ssmShiro.entity.User;
import com.ssmShiro.entity.UserRole;
import com.ssmShiro.entity.dto.PageInfo;
import com.ssmShiro.service.UserService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 
 * @FileName: UserServiceBean.java
 * @Description: 人员业务逻辑实现类 
 * @author: yinghui.zhang
 * @email: uuhui@163.com 
 * @date: 2018年3月27日 
 * @version: V1.0
 */
@Service("userService")
public class UserServiceBean extends BaseServiceBean<User> implements UserService{
    @Resource
    private UserRoleMapper userRoleMapper;
    
 
    @Override
    public User selectByUsername(String username)throws Exception{
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        List<User> userList = selectByExample(example);
        if(userList.size()>0){
            return userList.get(0);
        }
            return null;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public int delUser(Integer userid) throws Exception{
        //删除用户表
        mapper.deleteByPrimaryKey(userid);
        //删除用户角色表
        Example example = new Example(UserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userid",userid);
       return  userRoleMapper.deleteByExample(example);
    }

	 

	@Override
	public List<User> getList(User entity) throws Exception {
		return super.selectByExample(getExample(entity));
	}
	
	public Example getExample(User entity){
		Example example=new Example(entity.getClass());
		if(entity!=null){
			Criteria criteria=example.createCriteria();
			if(StringUtils.hasText(entity.getUsername())){//按名称模糊查询
				criteria.andLike("userName", entity.getUsername().trim());
			}
			if(entity.getEnable()!=null){
				criteria.andEqualTo("enable",entity.getEnable());
			}
		}
		return example;
	}

	@Override
	public PageInfo<User> selectByPage(PageInfo<User> page, User entity) throws Exception {
		return super.selectByPage(page, getExample(entity));
	}
	 
}
